package cn.wangxl.group.rpc.server;

import cn.wangxl.group.rpc.handler.RequestHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 * @Description NettyServerHandler
 * @Classname NettyServerHandler
 * @Created by wangxl
 * @Date 2020/2/9 0:41
 */
//@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private RequestHandler requestHandler;

    private byte[] rspData;

    private byte[] reqData;


    public NettyServerHandler(RequestHandler requestHandler) {
        this.requestHandler = requestHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("正在读取消息");

        ByteBuf in = (ByteBuf)msg;
        int readableBytes = in.readableBytes();
        reqData =new byte[readableBytes];
        in.readBytes(reqData);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        System.out.println("读取消息完毕");
        rspData = requestHandler.handleRequest(reqData);
        super.channelReadComplete(ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer(rspData)).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常");
        super.exceptionCaught(ctx, cause);

        cause.printStackTrace();
    }
}
